<template>
    <div class="poyline-dialog">
        <el-dialog v-model="compState.dialogVisible" :title="props.operateType == 'add' ? '新增线路' : '修改线路'" width="40%"
            @close="handleClose" @open="handleOpen" :modal="false" :append-to-body="true" :close-on-click-modal="false">
            <el-form ref="formRef" :inline="true" :model="formPoyline" class="demo-form-inline" :rules="formRules"
                :label-width="100">
                <el-form-item label="线路Id" v-if="props.operateType == 'add' ? false : true">
                    <el-input v-model="props.poylineId" placeholder="" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="活动" prop="activityValue">
                    <el-select v-model="formPoyline.activityValue" placeholder="请选择活动">
                        <el-option v-for="item in formPoyline.activityOptions" :key="item.Code" :label="item.Name"
                            :value="item.Code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="城市" prop="cityValue">
                    <el-select v-model="formPoyline.cityValue" placeholder="请选择城市">
                        <el-option v-for="item in formPoyline.cityOptions" :key="item.Code" :label="item.Name"
                            :value="item.Code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="场馆" prop="venueValue">
                    <el-select v-model="formPoyline.venueValue" placeholder="请选择场馆" @visible-change="handleVisibleChange">
                        <el-option v-for="item in formPoyline.venueOptions" :key="item.Code" :label="item.Name"
                            :value="item.Code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="线路名称" prop="poylineName">
                    <el-input v-model="formPoyline.poylineName" placeholder="请输入线路名称"></el-input>
                </el-form-item>
                <el-form-item label="透明度" prop="strokeOpacity">
                    <el-select v-model="formPoyline.strokeOpacity" placeholder="请选择透明度">
                        <el-option v-for="i in 10" :label="((i * 0.1).toFixed(1))" :value="((i * 0.1).toFixed(1))" />
                    </el-select>
                </el-form-item>
                <el-form-item label="边线宽度" prop="strokeWeight">
                    <el-select v-model="formPoyline.strokeWeight" placeholder="请选择边线宽度">
                        <el-option v-for="i in 10" :label="i" :value="i" />
                    </el-select>
                </el-form-item>
                <el-form-item label="边线样式" prop="strokeStyle">
                    <el-select v-model="formPoyline.strokeStyle" placeholder="请选择边线样式">
                        <el-option label="实线" value="solid" />
                        <el-option label="虚线" value="dashed" />
                    </el-select>
                </el-form-item>
                <el-form-item label="线路颜色" prop="strokeColor">
                    <el-color-picker v-model="formPoyline.strokeColor" />
                </el-form-item>
                <el-form-item label="是否有效" prop="whetherValid">
                    <el-select v-model="formPoyline.whetherValid" placeholder="请选择是否有效">
                        <el-option label="有效" :value=1 />
                        <el-option label="无效" :value=0 />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="是否显示" prop="whetherShow">
                    <el-select v-model="formPoyline.whetherShow" placeholder="请选择是否显示">
                        <el-option label="显示" value= 1 />
                        <el-option label="不显示" value= 0 />
                    </el-select>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCancel(formRef)">取消</el-button>
                    <el-button type="primary" @click="handleConfirm(formRef)">
                        {{ props.operateType == 'add' ? '确定新增' : '确定修改' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { getReturnEntity } from '../class/EntityMethod'
import {
    InsertMarkLine,
    UpdateMarkLine,
    MarkLine
} from '../../../network/poyline'
import { QueryCity, QueryVenue, QueryActivity } from '../../../network/childCity'
import { ElMessage, ElMessageBox } from 'element-plus'
import { setupMapState } from "../../../store/utils/hook"
const { userInfoVx } = setupMapState("app", ["userInfoVx"])
const emit = defineEmits(['closePoylineDrawEmit', 'clearCurPoylineDrawEmit', 'getPoylineIdEmit', 'showAddpoylineEmit'])
const props = defineProps({
    dialogVisibleNum: {
        type: Number,
        default: () => 1
    },
    operateType: {
        type: String,
        default: () => ''
    },
    allPoints: {
        type: Array,
        default: () => []
    },
    poylineId: {
        type: Number,
        default: () => -1
    }
})

const formRef = ref()
const compState = reactive({
    isOpen: false,
    polylineDraw: null,
    dialogVisible: false,
    scene: null,
    poylinedata: null,
    operateType: "",
})
const formPoyline = reactive({
    poylineName: "",
    strokeColor: 'red',//边线颜色
    strokeWeight: 3,//边线的宽度，以像素为单位
    strokeOpacity: 0.8,//边线透明度，取值范围0 - 1
    strokeStyle: 'solid',//solid or dashed
    whetherValid: 1,
    whetherShow: 1,

    activityValue: 1,
    activityOptions: [],
    cityValue: 2,
    cityOptions: [],
    venueValue: "",
    venueOptions: [],

    pointsArr: []
})
// 自定义校验
const validNullValue = (rule, val, callback) => {
    // console.log(val)
    if (val == "") {
        callback(new Error("必填！"))
    } else {
        callback()
    }
}
const formRules = ref({
    activityValue: [{
        validator: validNullValue,
        trigger: "change"
    }],
    cityValue: [{
        validator: validNullValue,
        trigger: "change"
    }],
    venueValue: [{
        validator: validNullValue,
        trigger: "change"
    }],
    poylineName: [{
        validator: validNullValue,
        trigger: "blur"
    }],
})

watch(() => props.dialogVisibleNum, () => {
    compState.dialogVisible = true
})

// 弹窗打开
const handleOpen = async () => {
    // 活动下拉
    await QueryActivity().then(res => {
        // console.log(res)
        formPoyline.activityOptions = res
    }).catch(err => {
        console.log(err)
    })
    // 城市下拉
    await QueryCity().then(res => {
        // console.log(res)
        formPoyline.cityOptions = res
    }).catch(err => {
        console.log(err)
    })

    if (props.operateType == 'update') {
        // 根据id请求数据,赋值
        MarkLine({
            ID: props.poylineId
        }).then(res => {
            // console.log(res)
            if (res && res?.length > 0) {
                formPoyline.poylineId = res[0].ID
                formPoyline.activityValue = res[0].ActivityCode
                formPoyline.cityValue = res[0].CityCode
                formPoyline.venueValue = res[0].VenueCode
                formPoyline.poylineName = res[0].PathName
                formPoyline.strokeOpacity = res[0].Pellucidity
                formPoyline.strokeWeight = res[0].Width
                formPoyline.strokeColor = res[0].Colour
                formPoyline.strokeStyle = res[0].Pattern
                formPoyline.whetherValid = res[0].IsValid
            }
        }).catch(err => {
            console.log(err)
        })
    }
}
// 下拉显示触发
const handleVisibleChange = () => {
    let userCode = userInfoVx.value.UserCode
    let roleCode = userInfoVx.value.RoleCode
    // 场馆下拉
    QueryVenue({
        ActivityCode: formPoyline.activityValue,
        CityCode: formPoyline.cityValue,
        UserCode: userCode,
        RoleCode: roleCode
    }).then(res => {
        // console.log(res)
        formPoyline.venueOptions = res
    }).catch(err => {
        console.log(err)
    })
}
const handleCancel = () => {
    handleClose()
}
const handleConfirm = (formEl) => {
    // console.log(props.allPoints)
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            // 存经纬度
            formPoyline.pointsArr = props.allPoints
            // 格式化参数
            let paramEntity = getReturnEntity(formPoyline)
            // 请求Api  
            if (props.operateType == 'add') {//新增
                // 数据库中的字段是自增的
                paramEntity.ID = 0
                ElMessageBox.confirm(
                    '确定新增此线路？',
                    'Warning',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(async () => {
                    await InsertMarkLine(paramEntity).then(res => {
                        // console.log(res)
                        if (res == true) {
                            // 向父组件发送事件显示线路
                            emit('showAddpoylineEmit', formPoyline)
                            compState.dialogVisible = false
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                    ElMessage({ type: 'info', message: '新增取消了！', })
                })
            } else {//修改
                ElMessageBox.confirm(
                    '确定修改此线路？',
                    'Warning',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(async () => {
                    await UpdateMarkLine(paramEntity).then(res => {
                        // console.log(res)
                        if (res == true) {
                            emit('showAddpoylineEmit', formPoyline)
                            compState.dialogVisible = false
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                    ElMessage({ type: 'info', message: '修改取消了！', })
                })
            }
        } else {
            console.log('error submit!')
        }
    })

}
const handleClose = () => {
    compState.dialogVisible = false
    if (!formRef.value) return
    formRef.value.resetFields()
    if (props.operateType == 'add') {
        emit("closePoylineDrawEmit")
    } else {
        emit("clearCurPoylineDrawEmit")
    }
}
</script>

<style scoped></style>